<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';
require  'ipdata/IpLocation.php';

function getAccountInfo($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/sms/service/AccountService/getAccountInfo', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] == 'success' ) {
		if(is_array($bodyArray['body']['data'])) {
			$rquota   = isset($bodyArray['header']['rquota'])             ? $bodyArray['header']['rquota']              : 0;
			$userId   = isset($bodyArray['body']['data'][0]['userId'])    ? $bodyArray['body']['data'][0]['userId']     : 0;
			$balance  = isset($bodyArray['body']['data'][0]['balance'])   ? $bodyArray['body']['data'][0]['balance']    : 0;
			$budget   = isset($bodyArray['body']['data'][0]['budget'])    ? $bodyArray['body']['data'][0]['budget']     : 0;
			$userStat = isset($bodyArray['body']['data'][0]['userStat'])  ? $bodyArray['body']['data'][0]['userStat']   : 0;
			$database->query( " UPDATE cfg_expand SET `userStat` = '{$userStat}', `budget` = '{$budget}', `balance` = '{$balance}', `userRquota` = '{$rquota}', `userMessage` = '', `lastDatetime` = NOW() WHERE userid = {$userId} ");
		}
	} else {
		$userMessage = serialize(isset( $bodyArray['header']['failures'][0]) ?  $bodyArray['header']['failures'][0] : []);
		$database->query( " UPDATE cfg_expand SET `userStat` = 888,  `userRquota` = 0, `userMessage` = '{$userMessage}', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
	}
}

function getAddress($address) {
	$arrChinese = [ '北京','上海','天津','广东','福建','海南','安徽','贵州','甘肃','广西','河北','河南','黑龙江','湖北','湖南','吉林','江苏','江西','辽宁','内蒙古','宁夏','青海','山东','山西','陕西','四川','西藏','新疆','云南','浙江','重庆','香港','台湾','澳门','日本' ];
	$arrEnglish = [ 1000,2000,3000,4000,5000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000,18000,19000,20000,21000,22000,23000,24000,25000,26000,27000,28000,29000,30000,31000,32000,33000,34000,35000,36000,200000 ];
	$location = new IpLocation('ipdata/qqwry.dat');
	$getAddrName = $location->getAddrName($address);
	foreach ( $arrChinese as $index => $value ) {
		if( stripos($getAddrName, $value) !== false ) {
			return $arrEnglish[$index];
		}
	}
	return 300000;
}

function getStaySecond($database, $companyId, $userid, $userType) {
	$queryExpand = $database->query("SELECT `id`, `ocpcTime` FROM cfg_expand where `companyId` = {$companyId} AND `userType` = {$userType} AND `userid` = '{$userid}' LIMIT 1");
	if( isset($queryExpand[0]['id']) ) {
		if( $queryExpand[0]['ocpcTime'] > 0 ){
			return $queryExpand[0]['ocpcTime'];
		}
	}
	$querySystem = $database->query("SELECT `baiduocpc` FROM cfg_system where `companyId` = {$companyId} LIMIT 1");
	if( isset($querySystem[0]['baiduocpc']) ) {
		if( $querySystem[0]['baiduocpc'] > 0 ){
			return $querySystem[0]['baiduocpc'];
		}
	}
	return false;
}

function setSemCopySearchData ($database) {
    $copyEndData = date("Y-m-d H:i:s");
    $copyStartData = date("Y-m-d H:i:s", strtotime("-8 hours"));
    $queryCopyList = $database->query("SELECT `id`, `companyId`, `userid`, `word`, `keywordId`, `copyTime`, `staySecond` FROM cfg_copy where userType = 1 AND `vid` IS NOT NULL AND `word` IS NOT NULL AND `syncsearch` = 0 AND `copyTime` BETWEEN '{$copyStartData}' AND '{$copyEndData}'");
    if ($queryCopyList === false) {
    	showMessage($database->errno . ' - ' . $database->error);
    	return;
    }
    foreach ($queryCopyList as $value) {
    	$staySecond = getStaySecond($database, $value['companyId'], $value['userid'], 1);
    	if( $staySecond ) {
    		if( $value['staySecond'] > $staySecond ) {
    			$copyStartTime = strtotime(date("Y-m-d 00:00:00", strtotime($value['copyTime'])));
    			$copyEndTime   = $copyStartTime + 86400;
    			$querySearch = $database->query("SELECT `id`, (`copynumber` + 1) as `copynumber`, `cost` FROM cfg_search where `companyId` = {$value['companyId']} AND `userType` = 1 AND `userid` = '{$value['userid']}'
    				AND `word` = '{$value['word']}' AND `keywordid` = '{$value['keywordId']}' AND `datatime` BETWEEN '{$copyStartTime}' AND '{$copyEndTime}' LIMIT 1");
    			if( isset($querySearch[0]['id']) ) {
    				$copynumber = $querySearch[0]['copynumber'];
    				$copycost   = bcdiv($querySearch[0]['cost'], $copynumber, 2);
    				$database->query( " UPDATE cfg_copy SET `syncsearch` = 1 WHERE id = '{$value['id']}'; ");
    				$database->query( " UPDATE cfg_search SET `copynumber` = '{$copynumber}', `copycost` = '{$copycost}' WHERE id = '{$querySearch[0]['id']}'; ");
    			}
    		}
    	}
    }
}

function setSemCopyAreaData ($database) {
    $copyEndData = date("Y-m-d 00:00:00");
    $copyStartData = date("Y-m-d H:i:s", strtotime("-72 hours"));
    $queryCopyList = $database->query("SELECT `id`, `companyId`, `userid`, `word`, `keywordId`, `copyTime`, `ip`, `staySecond` FROM cfg_copy where userType = 1 AND `vid` IS NOT NULL AND `word` IS NOT NULL AND `syncarea` = 0 AND `copyTime` BETWEEN '{$copyStartData}' AND '{$copyEndData}'");
    if ($queryCopyList === false) {
    	showMessage($database->errno . ' - ' . $database->error);
    	return;
    }
    foreach ($queryCopyList as $value) {
    	$staySecond = getStaySecond($database, $value['companyId'], $value['userid'], 1);
    	if( $staySecond ) {
    		if( $value['staySecond'] > $staySecond ) {
    			$areaid = getAddress($value['ip']);
    			$copyStartTime = strtotime(date("Y-m-d 00:00:00", strtotime($value['copyTime'])));
    			$copyEndTime   = $copyStartTime + 86400;
    			$queryArea = $database->query("SELECT `id`, (`copynumber` + 1) as `copynumber`, `cost` FROM cfg_area where `companyId` = {$value['companyId']} AND `userType` = 1  AND `userid` = '{$value['userid']}'
    					AND `areaid` = '{$areaid}' AND `datatime` BETWEEN '{$copyStartTime}' AND '{$copyEndTime}' LIMIT 1");
    			if( isset($queryArea[0]['id']) ) {
    				$copynumber = $queryArea[0]['copynumber'];
    				$copycost   = bcdiv($queryArea[0]['cost'], $copynumber, 2);
    				$database->query( " UPDATE cfg_copy SET `syncarea` = 1 WHERE id = '{$value['id']}'; ");
    				$database->query( " UPDATE cfg_area SET `copynumber` = '{$copynumber}', `copycost` = '{$copycost}' WHERE id = '{$queryArea[0]['id']}'; ");
    			}
    		}
    	}
    }
}

function setSemCopyHoursData ($database) {
	$copyEndData = date("Y-m-d H:i:s");
	$copyStartData = date("Y-m-d H:i:s", strtotime("-72 hours"));
	$queryCopyList = $database->query("SELECT `id`, `companyId`, `userid`, `word`, `keywordId`, `copyTime`, `ip`, `staySecond` FROM cfg_copy where userType = 1 AND `vid` IS NOT NULL AND `word` IS NOT NULL AND `syncHours` = 0 AND `copyTime` BETWEEN '{$copyStartData}' AND '{$copyEndData}'");
	if ($queryCopyList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
    foreach ($queryCopyList as $value) {
    	$staySecond = getStaySecond($database, $value['companyId'], $value['userid'], 1);
    	if( $staySecond ) {
    		if( $value['staySecond'] > $staySecond ) {
    			$startTime = strtotime(date("Y-m-d H:00:00", strtotime($value['copyTime'])));
    			$endTime  = $startTime + 3600;
    			$queryHours = $database->query("SELECT `id`, (`copynumber` + 1) as `copynumber`, `cost` FROM cfg_hours where `companyId` = {$value['companyId']} AND `userType` = 1  AND `userid` = '{$value['userid']}'
    				AND `datatime` BETWEEN '{$startTime}' AND '{$endTime}' LIMIT 1");
    			if( isset($queryHours[0]['id']) ) {
    				$copynumber = $queryHours[0]['copynumber'];
    				$copycost   = bcdiv($queryHours[0]['cost'], $copynumber, 2);
    				$database->query( " UPDATE cfg_copy SET `syncHours` = 1 WHERE id = '{$value['id']}'; ");
    				$database->query( " UPDATE cfg_hours SET `copynumber` = '{$copynumber}', `copycost` = '{$copycost}' WHERE id = '{$queryHours[0]['id']}'; ");
    			}
    		}
    	}
    }
}

function uploadConvertData($database, $value) {
	$queryExpand = $database->query("SELECT `id`, `ocpc` FROM cfg_expand where `companyId` = '{$value['companyId']}' AND `userType` = '{$value['userType']}' AND `userid` = '{$value['userid']}' LIMIT 1");
	if( isset($queryExpand[0]['id']) ) {
		if($queryExpand[0]['ocpc']) {
			$reqData = json_encode(['token' => $queryExpand[0]['ocpc'], 'conversionTypes' => [[ 'logidUrl' => $value['url'], 'convertType' => $value['ocpcCode'] ]]]);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_URL, 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData');
			curl_setopt($ch, CURLOPT_POSTFIELDS, $reqData);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
			curl_setopt($ch, CURLOPT_HTTPHEADER, array (
				'Content-Type: application/json; charset=utf-8',
				'Content-Length: ' . strlen($reqData)
				)
			);
			for ($i = 0; $i < 5; $i++) {
				$response = curl_exec($ch);
				$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				if ($httpcode === 200) {
					$data = json_decode($response, true);
					$status = $data['header']['status'];
					if ( $status !== 4 ) {
						curl_close($ch);
						return $status === 0;
					}
				}
			}
			curl_close($ch);
			return false;
		}
	}
	return false;
}

function setOcpcReport($database) {

	// 最近24小时内OCPC回传
	$copyEndData = date("Y-m-d H:i:s");
	$copyStartData = date("Y-m-d H:i:s", strtotime("-24 hours"));

	// 百度搜索OCPC线索上报
	$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 2 WHERE `userType` = 1 AND `ocpcStatus` = 1 AND `vid` IS NULL; ");
	//$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 2 WHERE `userType` = 1 AND `ocpcStatus` = 1 AND `keywordId` IS NULL;  ");
	$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 3 WHERE `userType` = 1 AND `ocpcStatus` = 1 AND `copyTime` < '{$copyStartData}'; ");
	$queryCopyList = $database->query("SELECT `id`, `companyId`, `userid`, `vid`, `staySecond`, `keywordId`, `url`, `ocpcCode`, `userType` FROM cfg_copy where userType = 1
   	AND `ocpcStatus` = 1 AND `ocpcType` = 1 AND `copyTime` BETWEEN '{$copyStartData}' AND '{$copyEndData}'");
	foreach ($queryCopyList as $value) {
		$staySecond = getStaySecond($database, $value['companyId'], $value['userid'], 1);
		if( $staySecond ) {
			if( $value['staySecond'] > $staySecond ) {
				$queryOcpcLog = $database->query("SELECT `id` FROM cfg_ocpclog where `url` = '{$value['url']}' LIMIT 1");
				if( isset($queryOcpcLog[0]['id']) ) {
					$database->query( " UPDATE cfg_copy SET `ocpcStatus` = 4 WHERE id = '{$value['id']}'; ");
				} else {
					$status = uploadConvertData($database, $value);
					if( $status ) {
						$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 5, `ocpcTime` = NOW() WHERE `id` = {$value['id']}; ");
						$database->query( " INSERT INTO cfg_ocpclog ( `url`, `datatime` ) values ( '{$value['url']}', NOW()) " );
					}
				}
			} else {
				$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 2 WHERE `ocpcStatus` = 1; ");
			}
		}
	}

	// 百度信息流OCPC线索上报
	$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 2 WHERE `userType` = 2 AND `ocpcStatus` = 1 AND `vid` IS NULL; ");
	$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 3 WHERE `userType` = 2 AND `ocpcStatus` = 1 AND `copyTime` < '{$copyStartData}'; ");
	$queryCopyList = $database->query("SELECT `id`, `companyId`, `userid`, `vid`, `staySecond`, `url`, `ocpcCode`, `userType` FROM cfg_copy where userType = 2
   	AND `ocpcStatus` = 1 AND `ocpcType` = 1 AND `copyTime` BETWEEN '{$copyStartData}' AND '{$copyEndData}'");
	foreach ($queryCopyList as $value) {
		$staySecond = getStaySecond($database, $value['companyId'], $value['userid'], 2);
		if( $staySecond ) {
			if( $value['staySecond'] > $staySecond ) {
				$queryOcpcLog = $database->query("SELECT `id` FROM cfg_ocpclog where `url` = '{$value['url']}' LIMIT 1");
				if( isset($queryOcpcLog[0]['id']) ) {
					$database->query( " UPDATE cfg_copy SET `ocpcStatus` = 4 WHERE id = '{$value['id']}'; ");
				} else {
					$status = uploadConvertData($database, $value);
					if( $status ) {
						$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 5, `ocpcTime` = NOW() WHERE `id` = {$value['id']}; ");
						$database->query( " INSERT INTO cfg_ocpclog ( `url`, `datatime` ) values ( '{$value['url']}', NOW()) " );
					}
				}
			} else {
				$database->query( " UPDATE `cfg_copy` SET `ocpcStatus` = 2 WHERE `ocpcStatus` = 1; ");
			}
		}
	}

}

function setServiceCount($database) {
	$queryServiceList = $database->query("SELECT `companyId`, `platform`, `bazaarId`, `zoneid`, `name`, `nickname`, `wechat` FROM cfg_service");
	foreach ($queryServiceList as $value) {
		$datetime = date("Y-m-d 01:01:01", strtotime("-1 day"));
		$cost = 0;
		$queryKeywordId = $database->query("SELECT `keywordId` FROM cfg_copy where `companyId` = '{$value['companyId']}' AND `wechat` = '{$value['wechat']}' AND to_days(`copyTime`) = to_days('$datetime')");
		if( count($queryKeywordId) > 0 ) {
			$keywordIdArray = [];
			foreach ($queryKeywordId as $temp) {
				array_push($keywordIdArray, $temp['keywordId']);
			}
			$keywordIdstr = implode(',', $keywordIdArray);
			$searchStartTime = strtotime(date("Y-m-d 00:00:00", strtotime($datetime)));
			$searchEndTime   = $searchStartTime + 86400;
			$querysearchnumber = $database->query("SELECT sum(`id`) as `copycost` FROM cfg_search where `companyId` = '{$value['companyId']}' AND `keywordid` in ($keywordIdstr) AND `datatime` BETWEEN '{$searchStartTime}' AND '{$searchEndTime}'");
			if(isset($querysearchnumber[0]['copycost'])) {
				$cost = $querysearchnumber[0]['copycost'];
			}
		}
		$shownumber = 0;
		$queryshownumber = $database->query("SELECT count(`id`) as `number` FROM cfg_access where `companyId` = '{$value['companyId']}' AND `service` LIKE '%{$value['wechat']}%' AND to_days(`accessTime`) = to_days('$datetime')");
		if(isset($queryshownumber[0]['number'])) {
			$shownumber = $queryshownumber[0]['number'];
		}
		$copynumber = 0;
		$querycopynumber = $database->query("SELECT count(`id`) as `number` FROM cfg_copy where `companyId` = '{$value['companyId']}' AND `wechat` = '{$value['wechat']}' AND to_days(`copyTime`) = to_days('$datetime')");
		if(isset($querycopynumber[0]['number'])) {
			$copynumber = $querycopynumber[0]['number'];
		}
		$queryAnalyse = $database->query("SELECT `id` FROM cfg_service_analyse where `wechat` = '{$value['wechat']}' AND to_days(`datetime`) = to_days('$datetime') LIMIT 1");
		if( isset($queryAnalyse[0]['id']) ) {
			$database->query( " UPDATE cfg_service_analyse SET `shownumber` = '{$shownumber}', `copynumber` = '{$copynumber}', `cost` = '{$cost}' WHERE `id` = {$queryAnalyse[0]['id']} ");
		} else {
			$database->query( " INSERT INTO cfg_service_analyse ( `companyId`, `platform`, `bazaarId`, `zoneid`, `name`, `nickname`, `wechat`, `datetime`, `shownumber`, `copynumber`, `cost` ) values (
			  '{$value['companyId']}', '{$value['platform']}', '{$value['bazaarId']}', '{$value['zoneid']}', '{$value['name']}', '{$value['nickname']}', '{$value['wechat']}', '{$datetime}', {$shownumber}, {$copynumber}, {$cost}) " );
		}
	}
}

function setFeedCopySearchData($database) {
	$queryCampaign = $database->query("SELECT `id`, `companyId`, `userId`, `campaignId` FROM cfg_campaign where `userType` = 2");
	foreach ($queryCampaign as $value) {
		$adgroupIdArray = [];
		$queryAdgroup = $database->query("SELECT `id`, `adgroupId` FROM cfg_adgroup where `companyId` = '{$value['companyId']}' AND `userType` = 2 AND `userId` = '{$value['userId']}' AND `campaignId` = '{$value['campaignId']}'");
		foreach ($queryAdgroup as $value1) {
			array_push($adgroupIdArray, $value1['adgroupId']);
		}
		if(count($adgroupIdArray) > 0 ) {
			$adgroupIdStr = implode(',', $adgroupIdArray);
			$datetimeEx = strtotime(date("Y-m-d 00:00:00", strtotime("-3 day")));
			$querySearchNumber = $database->query(" SELECT FROM_UNIXTIME(`datatime`,'%Y-%m-%d 00:00:00') as `datatime`, sum(`copynumber`) as `copynumber`, sum(`copycost`) as `copycost` FROM `cfg_search`
			  where `userType` = 2 AND `datatime` > $datetimeEx AND `adgroupid` in ($adgroupIdStr) group by `datatime` ;");
			foreach ($querySearchNumber as $value2) {
				if ( $value2['copynumber'] > 0 ) {
					$startTime = strtotime($value2['datatime']);
					$endTime = $startTime + 86400;
					$database->query( " UPDATE `cfg_search` SET `copynumber` = '{$value2['copynumber']}', `copycost` = '{$value2['copycost']}' WHERE `userType` = 2
						 AND `campaignid` = {$value['campaignId']} AND `datatime` BETWEEN '{$startTime}' AND '{$endTime}'");
				}
			}
		}
	}
}

function sendsms($data) {
	$results = '';
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json' );
	curl_setopt ( $ch, CURLOPT_POST, true );
	curl_setopt ( $ch, CURLOPT_HEADER, false);
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query($data));
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, ['Accept:application/json;charset=utf-8;',
	  'Content-Type:application/x-www-form-urlencoded;charset=utf-8;'] );
	$results = curl_exec ( $ch );
	if(empty($results)) {
		curl_close ($ch );
		return ['code'=>8888, 'msg' => '网络波动异常'];
	}
	curl_close ($ch );
	return json_decode($results, true);
}

function initializeSms($database, $companyId, $phone, $message) {
    $array = explode(',', $phone);
    if(stripos($message, "，当前余额") === false) {
    	foreach ($array as $value) {
    		if( strlen ($value) == 11 ) {
    			$query = $database->query("SELECT `id` FROM cfg_smslog where `companyId` = '{$companyId}' AND `phone` = '{$value}' AND `content` = '{$message}' AND to_days(`datetime`) = to_days(now()) LIMIT 1");
    			if( !isset($query[0]['id']) ) {
    				$database->query( " INSERT INTO cfg_smslog ( `companyId`, `phone`, `status`, `content`, `datetime` ) values ( '{$companyId}', '{$value}', 1, '{$message}', now() ) " );
    			}
    		}
    	}
    	return;
    }
    $_message = $message;
    $_explode = explode("，当前余额",  $message);
    if( count( $_explode) ==2) {
        $_message = $_explode[0];
    }
	foreach ($array as $value) {
		if( strlen ($value) == 11 ) {
			$query = $database->query("SELECT `id` FROM cfg_smslog where `companyId` = '{$companyId}' AND `phone` = '{$value}' AND `content` LIKE '{$_message}%' AND to_days(`datetime`) = to_days(now()) LIMIT 1");
			if( !isset($query[0]['id']) ) {
				$database->query( " INSERT INTO cfg_smslog ( `companyId`, `phone`, `status`, `content`, `datetime` ) values ( '{$companyId}', '{$value}', 1, '{$message}', now() ) " );
			}
		}
	}
 
}

function isUserExcessive($database, $companyId, $userType, $userId, $maxValue) {
	if(empty($maxValue)) {
		return false;
	}

	$startDatatime = strtotime(date("Y-m-d 00:00:00"));
	$endDatatime = $startDatatime + 86400;
	if( $userType == 1) {
		$query = $database->query("SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
		if( !isset($query[0]['cost']) ){
			return false;
		}
		if(empty($query[0]['cost'])) {
			return false;
		}
		if(empty($query[0]['number'])) {
			return false;
		}
		$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
		if( $bcdiv > $maxValue) {
			return true;
		}
		return false;
	}
	$query = $database->query("SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `campaignid` > 0 AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
	if( !isset($query[0]['cost']) ){
		return false;
	}
	if(empty($query[0]['cost'])) {
		return false;
	}
	if(empty($query[0]['number'])) {
		return false;
	}
	$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
	if( $bcdiv > $maxValue) {
		return true;
	}
	return false;
}

function isPlanExcessive($database, $companyId, $userType, $userId, $maxValue) {
	if(empty($maxValue)) {
		return false;
	}
	$startDatatime = strtotime(date("Y-m-d 00:00:00"));
	$endDatatime = $startDatatime + 86400;
	if( $userType == 1) {
		$campaignIdArray = [];
		$query = $database->query("SELECT `campaignId` FROM cfg_campaign where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userId` = '{$userId}' ");
		if( count($query) == 0) {
			return false;
		}
		foreach( $query as $value ) {
			array_push($campaignIdArray, $value['campaignId']);
		}
		$campaignIdStr = implode(',', $campaignIdArray);
		$query = $database->query(" SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search
			where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `campaignid` in ($campaignIdStr) AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
		if( !isset($query[0]['cost']) ){
			return false;
		}
		if(empty($query[0]['cost'])) {
			return false;
		}
		if(empty($query[0]['number'])) {
			return false;
		}
		$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
		if( $bcdiv > $maxValue) {
			return true;
		}
		return false;
	}
	$query = $database->query("SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `campaignid` > 0 AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
	if( !isset($query[0]['cost']) ){
		return false;
	}
	if(empty($query[0]['cost'])) {
		return false;
	}
	if(empty($query[0]['number'])) {
		return false;
	}
	$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
	if( $bcdiv > $maxValue) {
		return true;
	}
	return false;
}

function isUnitExcessive($database, $companyId, $userType, $userId, $maxValue) {
	if(empty($maxValue)) {
		return false;
	}

	$startDatatime = strtotime(date("Y-m-d 00:00:00"));
	$endDatatime = $startDatatime + 86400;
	if( $userType == 1) {
		$adgroupIdArray = [];
		$query = $database->query("SELECT `adgroupId` FROM cfg_adgroup where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userId` = '{$userId}' ");
		if( count($query) == 0) {
			return false;
		}
		foreach( $query as $value ) {
			array_push($adgroupIdArray, $value['adgroupId']);
		}
		$adgroupIdStr = implode(',', $adgroupIdArray);
		$query = $database->query(" SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search
			where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `adgroupid` in ($adgroupIdStr) AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
		if( !isset($query[0]['cost']) ){
			return false;
		}
		if(empty($query[0]['cost'])) {
			return false;
		}
		if(empty($query[0]['number'])) {
			return false;
		}
		$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
		if( $bcdiv > $maxValue) {
			return true;
		}
		return false;
	}

	$query = $database->query("SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `adgroupid` > 0 AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
	if( !isset($query[0]['cost']) ){
		return false;
	}
	if(empty($query[0]['cost'])) {
		return false;
	}
	if(empty($query[0]['number'])) {
		return false;
	}
	$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
	if( $bcdiv > $maxValue) {
		return true;
	}
	return false;
}

function isCreativeExcessive($database, $companyId, $userType, $userId, $maxValue) {
	if(empty($maxValue)) {
		return false;
	}

	$startDatatime = strtotime(date("Y-m-d 00:00:00"));
	$endDatatime = $startDatatime + 86400;
	if( $userType == 1){
		$creativeIdArray = [];
		$query = $database->query("SELECT `creativeId` FROM cfg_creative where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userId` = '{$userId}' ");
		if( count($query) == 0) {
			return false;
		}
		foreach( $query as $value ) {
			array_push($creativeIdArray, $value['creativeId']);
		}
		$creativeIdStr = implode(',', $creativeIdArray);
		$query = $database->query(" SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search
			where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `creativeid` in ($creativeIdStr) AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
		if( !isset($query[0]['cost']) ){
			return false;
		}
		if(empty($query[0]['cost'])) {
			return false;
		}
		if(empty($query[0]['number'])) {
			return false;
		}
		$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
		if( $bcdiv > $maxValue) {
			return true;
		}
		return false;
	}

	$query = $database->query("SELECT sum(`cost`) as `cost`, sum(`copynumber`) as `number` FROM cfg_search where `companyId` = '{$companyId}' AND `userType` = '{$userType}' AND `userid` = '{$userId}' AND `creativeid` > 0 AND `datatime` BETWEEN '{$startDatatime}' AND '{$endDatatime}'");
	if( !isset($query[0]['cost']) ){
		return false;
	}
	if(empty($query[0]['cost'])) {
		return false;
	}
	if(empty($query[0]['number'])) {
		return false;
	}
	$bcdiv = bcdiv($query[0]['cost'], $query[0]['number'], 0);
	if( $bcdiv > $maxValue) {
		return true;
	}
	return false;
}

function setCpaPolice($database) {
	$database->query( " UPDATE `cfg_smslog` SET `status` = 3 WHERE `datetime` < DATE_FORMAT(now(),'%Y-%m-%d 00:00:00') ");
	$queryExpand = $database->query("SELECT `id`, `companyId`, `contact`, `userType`, `username`, `userId`, `bazaarId`, `cpa`, `balance` FROM cfg_expand where `status` = 1 AND LENGTH(`cpa`) > 30 AND `bazaarId` > 0");
	foreach ($queryExpand as $value) {
		$value['bazaarName'] = null;
		$value['cpa'] = unserialize($value['cpa']);
		$queryBazaar = $database->query("SELECT `id`, `name` FROM cfg_bazaar where `id` = '{$value['bazaarId']}' LIMIT 1");
		if( isset($queryBazaar[0]['id']) ) {
			$value['bazaarName'] = $queryBazaar[0]['name'];
		}
		if($value['bazaarName']) {
			if( empty($value['contact']) ) {
				$user = $database->query("SELECT `id`, `username` FROM cfg_user where `companyId` = '{$value['companyId']}' AND `level` < 3 LIMIT 1");
				if( isset($user[0]['id']) ) {
					$value['contact'] = $user[0]['username'];
				}
			} else {
				$principal = $database->query("SELECT `name` FROM cfg_principal where `companyId` = '{$value['companyId']}' AND `id` = {$value['contact']} LIMIT 1");
				if( isset($principal[0]['name']) ) {
					$value['contact'] = $principal[0]['name'];
				}
			}

			$queryPerson = $database->query("SELECT `id`, `name` FROM cfg_bazaar where `id` = '{$value['bazaarId']}' LIMIT 1");
			if( isset($queryBazaar[0]['id']) ) {
				$value['bazaarName'] = $queryBazaar[0]['name'];
			}

			if($value['cpa']['mobileValue']) {
				$categoryName = $value['userType'] == 1 ? '竞价' : '信息流';
				$value['cpa']['balanceValue'] = isset($value['cpa']['balanceValue']) ? intval($value['cpa']['balanceValue']) : 0;
				if( $value['cpa']['balanceValue'] > 0 ) {
					if( intval($value['balance']) < $value['cpa']['balanceValue'] ) {
						initializeSms($database, $value['companyId'], $value['cpa']['mobileValue'], '【红蜘蛛】'.$value['contact'].'您好,您'.$value['bazaarName'] .'市场下的' . $categoryName . '“'.$value['username'].'”，账户余额已低于' . $value['cpa']['balanceValue'] . '元，当前余额'.$value['balance'].'元' );
					}
				}
				if($value['cpa']['userValue'] > 0 ) {
					$verify = isUserExcessive($database, $value['companyId'], $value['userType'], $value['userId'], $value['cpa']['userValue']);
					if($verify) {
						initializeSms($database, $value['companyId'], $value['cpa']['mobileValue'], '【红蜘蛛】'.$value['contact'].'您好,您'.$value['bazaarName'] .'市场下的' . $categoryName . '“'.$value['username'].'”，账户CPA已超出' . $value['cpa']['userValue']);
					}
				}
				if($value['cpa']['planValue'] > 0 ) {
					$verify = isPlanExcessive($database, $value['companyId'], $value['userType'], $value['userId'], $value['cpa']['planValue']);
					if($verify) {
					  initializeSms($database, $value['companyId'], $value['cpa']['mobileValue'], '【红蜘蛛】'.$value['contact'].'您好,您'.$value['bazaarName'] .'市场下的' . $categoryName . '“'.$value['username'].'”，计划CPA已超出' . $value['cpa']['planValue']);
					}
				}
				if($value['cpa']['unitValue'] > 0 ) {
					$verify = isUnitExcessive($database, $value['companyId'], $value['userType'], $value['userId'], $value['cpa']['unitValue']);
					if($verify) {
					  initializeSms($database, $value['companyId'], $value['cpa']['mobileValue'], '【红蜘蛛】'.$value['contact'].'您好,您'.$value['bazaarName'] .'市场下的' . $categoryName . '“'.$value['username'].'”，单元CPA已超出' . $value['cpa']['unitValue']);
				  }
				}
				if($value['cpa']['creativeValue'] > 0 ) {
					$verify = isCreativeExcessive($database, $value['companyId'], $value['userType'], $value['userId'], $value['cpa']['creativeValue']);
					if($verify) {
						initializeSms($database, $value['companyId'],  $value['cpa']['mobileValue'], '【红蜘蛛】'.$value['contact'].'您好,您'.$value['bazaarName'] .'市场下的' . $categoryName . '“'.$value['username'].'”，创意CPA已超出' . $value['cpa']['creativeValue']);
					}
				}
			}
		}
	}
}

function deleteInvalidData($database) {
 	$campaign = $database->query("SELECT `id`, `userId`, `userType` FROM cfg_campaign where `userType` BETWEEN 1 and 2 GROUP BY `userId`" );
	foreach ($campaign as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userId']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_campaign WHERE `userId` = '{$value['userId']}';");
		}
	}

 	$adgroup = $database->query("SELECT `id`, `userId`, `userType` FROM cfg_adgroup where `userType` BETWEEN 1 and 2 GROUP BY `userId`" );
	foreach ($adgroup as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userId']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_adgroup WHERE `userId` = '{$value['userId']}';");
		}
	}

 	$creative = $database->query("SELECT `id`, `userId`, `userType` FROM cfg_creative where `userType` BETWEEN 1 and 2 GROUP BY `userId`" );
	foreach ($creative as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userId']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_creative WHERE `userId` = '{$value['userId']}';");
		}
	}

 	$optlog = $database->query("SELECT `id`, `userId`, `userType` FROM cfg_optlog where `userType` BETWEEN 1 and 2 GROUP BY `userId`" );
	foreach ($optlog as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userId']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_optlog WHERE `userId` = '{$value['userId']}';");
		}
	}

 	$search = $database->query("SELECT `id`, `userid`, `userType` FROM cfg_search where `userType` BETWEEN 1 and 2 GROUP BY `userid`" );
	foreach ($search as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userid']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_search WHERE `userid` = '{$value['userid']}';");
		}
	}

 	$access = $database->query("SELECT `id`, `userid`, `userType` FROM cfg_access where `userType` BETWEEN 1 and 2 GROUP BY `userid`" );
	foreach ($access as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userid']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_access WHERE `userid` = '{$value['userid']}';");
		}
	}

 	$hours = $database->query("SELECT `id`, `userid`, `userType` FROM cfg_hours where `userType` BETWEEN 1 and 2 GROUP BY `userid`" );
	foreach ($hours as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userid']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_hours WHERE `userid` = '{$value['userid']}';");
		}
	}

 	$area = $database->query("SELECT `id`, `userid`, `userType` FROM cfg_area where `userType` BETWEEN 1 and 2 GROUP BY `userid`" );
	foreach ($area as $value) {
		$query = $database->query("SELECT `id` FROM cfg_expand where `userid` = '{$value['userid']}' AND `userType` = '{$value['userType']}' LIMIT 1");
		if( !isset($query[0]['id']) ) {
			$database->query("DELETE FROM cfg_area WHERE `userid` = '{$value['userid']}';");
		}
	}

}

run(function() use ($argv) {

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

    $currentTime = strtotime(date("H:i"));
    $startTime= strtotime('00:00');
    $endTime = strtotime('00:10');
    if($currentTime>=$startTime && $currentTime<=$endTime){
        showMessage('同步微信展示数.' );
        $database->query( " UPDATE `cfg_service` SET `number` = 0 ");
    }

	showMessage('同步信息流计划数据.' );
	setFeedCopySearchData($database);

	showMessage('同步竞价搜索词复制数.' );
	setSemCopySearchData($database);

	showMessage('同步竞价地区复制数.' );
	setSemCopyAreaData($database);

	showMessage('同步竞价时段复制数.' );
	setSemCopyHoursData($database);

	deleteInvalidData($database);

	showMessage('同步展示分析.' );
	setServiceCount($database);

	showMessage('同步OCPC上报.' );
	setOcpcReport($database);

	showMessage('同步CPA报警.' );
	setCpaPolice($database);

 	$querySmsArray = $database->query("SELECT `id`, `phone`, `content` FROM cfg_smslog where `status` = 1 " );
	foreach ($querySmsArray as $value) {
		go(function() use ($config, $value)  {
			$database = new MySQL;
			$connect = $database->connect($config);
			if( $connect === false) {
				return;
			}
			$sms = sendsms([
				'apikey' => '24a500765ca38055d82fe1a84711c8ff',
				'mobile' => $value['phone'],
				'text' => $value['content']
			]);
			if( $sms['code'] != 8888 ) {
				if( $sms['code'] == 0 ) {
					$database->query( " UPDATE `cfg_smslog` SET `status` = 2, `msg` = '{$sms['msg']}', `smstime` = now() WHERE `id` = '{$value['id']}' ");
				} else {
					$database->query( " UPDATE `cfg_smslog` SET `status` = 3, `msg` = '{$sms['msg']}', `smstime` = now() WHERE `id` = '{$value['id']}' ");
				}
			}
		});
	}

});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');